//
//  CategoryViewController.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/5/28.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "HomeSearchNaviView.h"
#import "CategoryViewController.h"
#import "productCellectionCell.h"
#import "ProductDetailViewController.h"
#import "CategoryTableViewCell.h"
#import "CategoryModel.h"
#import "UIView+Events.h"

@interface CategoryViewController ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate
> {
    
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
    BOOL _isCategoryHidden;
}
@property (nonatomic, strong) HomeSearchNaviView *naviView;

@property (nonatomic , strong) UICollectionView *categoryCollectionView;
@property (nonatomic, strong) NSMutableArray <ProductItemModel *>*productDataArray;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UIView *categoryView;
@property (nonatomic, strong) UITableView *FirstCategoryTableView;
@property (nonatomic, strong) UITableView *SecondCategoryTableView;
@property (nonatomic, strong) UIButton *hideBtn;

@property (nonatomic, strong) NSMutableDictionary *totalCategoryDic;
@property (nonatomic, strong) NSMutableArray <CategoryModel *>*firstCategoryDataArray;
@property (nonatomic, strong) NSMutableArray <CategoryModel *>*secondCategoryDataArray;

@property (nonatomic, copy) NSString *keyWord;
@property (nonatomic, copy) NSString *categoryID;

@end

@implementation CategoryViewController

- (void)dealloc {
    
}

-(void)showCategory:(NSNotification *)notification{
    
    _isCategoryHidden = !_isCategoryHidden;
    self.categoryView.hidden = _isCategoryHidden;
}

- (void)hideCategoryView {
    _isCategoryHidden = !_isCategoryHidden;
    self.categoryView.hidden = _isCategoryHidden;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    [self requestCategoryList];

    [self initView];
    [self prepareData];//刚进页面的时候初始化数据
    [self requestGoodList];
}

- (void)refreshParam{
    
    self.pageNum = 1;
    self.pageSize = 48;
    self.productDataArray = @[].mutableCopy;
}

- (void)prepareData {
    
    self.keyWord = @"";
    self.categoryID = @"";
    
    self.pageNum = (1);
    self.pageSize = (240);
    
    self.firstCategoryDataArray = @[].mutableCopy;
    self.secondCategoryDataArray = @[].mutableCopy;
    self.productDataArray = @[].mutableCopy;

}

- (void)doSearch {

    [self refreshParam];
    [self requestGoodList];
    [self.view endEditing:YES];

}

- (void)requestGoodList {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SEARCH_API];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:@(self.pageSize) forKey:@"pageSize"];
    [param setValue:@(self.pageNum) forKey:@"pageNum"];
    [param setValue:self.keyWord forKey:@"keyword"];
    [param setValue:self.categoryID forKey:@"categoryId"];
    
    WEAKSELF
    [TTHttpManager getRequestWithUrl:url TimeOut:10.0 GetData:param FinishBlock:^(id  _Nonnull data) {
        
        BOOL fail = [[data valueForKey:@"code"] boolValue];
        NSDictionary *resultDic = [data valueForKey:@"data"];
        if (!fail) {
            NSArray *resultArray = [resultDic valueForKey:@"result"];
            for (NSDictionary *goodsDic in resultArray) {
                ProductItemModel *model = [[ProductItemModel alloc] init];
                model.name = [goodsDic valueForKey:@"name"];
                model.path = [goodsDic valueForKey:@"path"];
                model.price = [goodsDic valueForKey:@"price"];
                model.productID = [goodsDic valueForKey:@"id"];
                [weakSelf.productDataArray addObject:model];
            }
            [weakSelf.categoryCollectionView reloadData];

        } else {
            [WHToast showErrorWithMessage:[resultDic valueForKey:@"message"] duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
            }];
        }

        [weakSelf.categoryCollectionView.mj_header endRefreshing];
        [weakSelf.categoryCollectionView.mj_footer endRefreshing];

    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.categoryCollectionView.mj_header endRefreshing];
        [weakSelf.categoryCollectionView.mj_footer endRefreshing];
    }];
    
}

- (void)requestCategoryList {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_CATEGORY_API];
    NSMutableDictionary *param = [NSMutableDictionary new];
    
    WEAKSELF
    [TTHttpManager getRequestWithUrl:url TimeOut:10.0 GetData:param FinishBlock:^(id  _Nonnull data) {
        
        BOOL fail = [[data valueForKey:@"code"] boolValue];
        NSDictionary *resultDic = [data valueForKey:@"data"];
        
        if (!fail) {
            weakSelf.totalCategoryDic = resultDic.mutableCopy;
            [weakSelf fillArrayWithDic:self.totalCategoryDic withIndex:0];
        } else {
            
            [WHToast showErrorWithMessage:[resultDic valueForKey:@"message"] duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
            }];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)fillArrayWithDic:(NSMutableDictionary *)dic withIndex:(NSInteger)index{
    
    NSArray *firstArr = [dic valueForKey:@"categorys"];
    for (int i = 0; i< firstArr.count; i++) {
        CategoryModel *firstModel = [[CategoryModel alloc] init];
        firstModel.categoryName = [firstArr[i] valueForKey:@"name"];
        firstModel.childrens = [firstArr[i] valueForKey:@"children"];
        [self.firstCategoryDataArray addObject:firstModel];
    }
    
    [self getSecondModelWitnIndex:index];
    [self.FirstCategoryTableView reloadData];
}

- (void)getSecondModelWitnIndex:(NSInteger)index {

    self.secondCategoryDataArray = @[].mutableCopy;
    NSArray *secondArray = self.firstCategoryDataArray[index].childrens;
    for (int i = 0; i<secondArray.count; i++) {
        CategoryModel *secondModel = [[CategoryModel alloc] init];
        secondModel.categoryName = [secondArray[i] valueForKey:@"name"];
        secondModel.categoryID = [secondArray[i] valueForKey:@"id"];
        [self.secondCategoryDataArray addObject:secondModel];
    }

    [self.SecondCategoryTableView reloadData];
}

- (void)initView {

    CGFloat width = self.view.frame.size.width - tabbarWidth;
    CGFloat height = self.view.frame.size.height;
    
    CGFloat cellWidth;
    CGFloat distance = 5;
    if (width > height) {
        cellWidth = width/4 - 2*distance;
    } else {
        cellWidth = width/3 - 2*distance;
    }
    _cellSize =  CGSizeMake(cellWidth, cellWidth/0.7);
    _collectionEdge = UIEdgeInsetsMake(distance, distance, distance, distance);
    
    [self.view addSubview:self.naviView];
    [self.view addSubview:self.categoryCollectionView];
    
    [self.view addSubview:self.categoryView];
    [self.categoryView addSubview:self.hideBtn];
    [self.categoryView addSubview:self.FirstCategoryTableView];
    [self.categoryView addSubview:self.SecondCategoryTableView];
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo([TT_SizeHelper getGlobalNavigationBarHeoght]);
        make.top.mas_equalTo(0);
    }];
    
    [self.categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    [self.FirstCategoryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(150);
    }];
    
    [self.SecondCategoryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.left.mas_equalTo(self.FirstCategoryTableView.mas_right).offset(0.5);
        make.width.mas_equalTo(150);
    }];
    
    [self.hideBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(0);
        make.left.mas_equalTo(self.SecondCategoryTableView.mas_left);
    }];
    
    [self.categoryCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.naviView.mas_bottom);
    }];
    

//    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
//    [self.categoryCollectionView addGestureRecognizer:singleTap];
}

#pragma mark --收起键盘
// 滑动空白处隐藏键盘
//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    [self.view endEditing:YES];
//}

// 点击空白处收键盘
//-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer {
//    [self.view endEditing:YES];
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showCategory:) name:categoryShowCategoryNoti object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];

    if (!_isCategoryHidden) {
        [self hideCategoryView];
    }
    [self.naviView.searchTextField resignFirstResponder];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:categoryShowCategoryNoti object:nil];
}

- (void)change
{
//    _cellSize =[self getCellSizeWithWidth:self.view.frame.size.height + 20];//加上状态栏高度
//    _collectionEdge = UIEdgeInsetsMake(1, 1, 1, 1);
//    [self.categoryCollectionView reloadData];
}

- (CGSize)getCellSizeWithWidth:(CGFloat)width {
    
    CGFloat cellWidth;
    
    CGFloat screenW = self.view.frame.size.width ;
    CGFloat screenH = self.view.frame.size.height - tabbarWidth;
    CGFloat distance = 5;
    if (screenW > screenH) {
        cellWidth = screenH/3 - 2 * distance;
    } else {
        cellWidth = screenH/4 - 2 * distance;
    }
    return  CGSizeMake(cellWidth, cellWidth/0.7);
}

- (HomeSearchNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[HomeSearchNaviView alloc] init];
        
        [_naviView.searchButton addTarget:self action:@selector(doSearch) forControlEvents:UIControlEventTouchUpInside];
        _naviView.searchTextField.delegate = self;
    }
    return _naviView;
}

#pragma mark 搜索框回调
- (void)textFieldDidEndEditing:(UITextField *)textField {
    self.keyWord = textField.text;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField.text.length) {
        self.keyWord = textField.text;
        [self doSearch];
        
    } else {
        
        [WHToast showErrorWithMessage:@"请输入搜索词再点击搜索" duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
        }];
    }

    return YES;
}

- (UICollectionView *)categoryCollectionView {
    if (!_categoryCollectionView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _categoryCollectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _categoryCollectionView.delegate = self;
        _categoryCollectionView.dataSource = self;
        _categoryCollectionView.backgroundColor = UIColorHex(0xf1f1f1);
        [_categoryCollectionView registerNib:[UINib nibWithNibName:@"productCellectionCell" bundle:nil] forCellWithReuseIdentifier:@"productCellectionCell"];
        
        WEAKSELF
        _categoryCollectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf requestGoodList];
        }];
        
        _categoryCollectionView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf requestGoodList];
        }];
    }
    return _categoryCollectionView;
}

- (UITableView *)FirstCategoryTableView {
    
    if (!_FirstCategoryTableView) {
        _FirstCategoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
        _FirstCategoryTableView.backgroundColor = UIColorHex(0xf1f1f1);
        _FirstCategoryTableView.delegate = self;
        _FirstCategoryTableView.dataSource = self;
        _FirstCategoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _FirstCategoryTableView.showsHorizontalScrollIndicator = NO;
        _FirstCategoryTableView.showsVerticalScrollIndicator = NO;
        _FirstCategoryTableView.tag = 1000;
        [_FirstCategoryTableView registerNib:[UINib nibWithNibName:@"CategoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"CategoryTableViewCellID"];
    }
    
    return _FirstCategoryTableView;
}

- (UITableView *)SecondCategoryTableView {
    if (!_SecondCategoryTableView) {
        _SecondCategoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
        _SecondCategoryTableView.backgroundColor = UIColorHex(0xf1f1f1);
        _SecondCategoryTableView.delegate = self;
        _SecondCategoryTableView.dataSource = self;
        _SecondCategoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _SecondCategoryTableView.showsHorizontalScrollIndicator = NO;
        _SecondCategoryTableView.showsVerticalScrollIndicator = NO;
        _SecondCategoryTableView.tag = 2000;
        [_SecondCategoryTableView registerNib:[UINib nibWithNibName:@"CategoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"CategoryTableViewCellID"];
    }
    return _SecondCategoryTableView;
}

- (UIView *)categoryView {
    if (!_categoryView) {
        _categoryView = [[UIView alloc] init];
        _categoryView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    }
    return _categoryView;
}

- (UIButton *)hideBtn {
    if (!_hideBtn) {
        _hideBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _hideBtn.backgroundColor = [UIColor clearColor];
        [_hideBtn addTarget:self action:@selector(hideCategoryView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _hideBtn;
}

#pragma mark CollectionView delegate & dataSource

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.productDataArray.count > indexPath.row) {
        ProductDetailViewController *productDetail = [[ProductDetailViewController alloc] init];
        productDetail.productID = self.productDataArray[indexPath.row].productID;
        [self.navigationController pushViewController:productDetail animated:YES];
    }
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView
                                   cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    productCellectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"productCellectionCell" forIndexPath:indexPath];
    [cell fillCellWithModel:self.productDataArray[indexPath.row]];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    return _cellSize;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return self.productDataArray.count;
}

//设置cell的位置
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section
{
    return _collectionEdge;
}

#pragma mark tableview delegate & dataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryTableViewCellID" forIndexPath:indexPath];
    

    switch (tableView.tag) {
        case 1000:{
            [cell fillCellWithModel:self.firstCategoryDataArray[indexPath.row]];
        }break;
        case 2000:{
            [cell fillCellWithModel:self.secondCategoryDataArray[indexPath.row]];
        }break;
            
        default:
            break;
    }
    

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger num = 10;
    switch (tableView.tag) {
        case 1000:{
            num = _firstCategoryDataArray.count;
        } break;
        case 2000:{
            num = _secondCategoryDataArray.count;
        } break;
            
        default:
            break;
    }
    return num;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (tableView.tag) {
        case 1000:{

            [self getSecondModelWitnIndex:indexPath.row];
            
        } break;
        case 2000:{

            if (self.secondCategoryDataArray.count > indexPath.row) {
                self.categoryID = self.secondCategoryDataArray[indexPath.row].categoryID;
                [self refreshParam];
                [self doSearch];
                [self hideCategoryView];
            }
        } break;
            
        default:
            break;
    }
}




@end
